package cn.lj.logistics.shiro;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.apache.shiro.web.util.WebUtils;

import cn.lj.logistics.pojo.User;

public class MyFormAuthenticationFilter extends FormAuthenticationFilter{

	
	protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
		//从请求中获取Shiro的 主体
		Subject subject = getSubject(request, response);
		//从主体中获取Shiro框架的Session
		Session session = subject.getSession();
		//如果主体没有认证（Session中认证）并且 主体已经设置记住我了
		if (!subject.isAuthenticated() && subject.isRemembered()) {
			//获取主体的身份（从记住我的Cookie中获取的）
			User principal = (User) subject.getPrincipal();
			//将身份认证信息共享到 Session中
			session.setAttribute("USER_IN_SESSION", principal);
		}
		return subject.isAuthenticated() || subject.isRemembered();
	}
	
	@Override
	protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request,
			ServletResponse response) throws Exception {
		//清除Shiro在Session保存的认证前最后一次请求的地址
		WebUtils.getAndClearSavedRequest(request);
		return super.onLoginSuccess(token, subject, request, response);
	}
	
	@Override
	protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
		
		 if (isLoginRequest(request, response)) {//判断是否是登录请求
	            if (isLoginSubmission(request, response)) {//判断是否是post
	            	HttpServletRequest req = (HttpServletRequest)request;
	            	// 1.获取请求对象的verifyCode验证码参数
	            	String verifyCode = req.getParameter("verifyCode");
	            	//2.获取session中随机数
	            	String rand=(String) req.getSession().getAttribute("rand");
	            	System.out.println("verifyCode :"+verifyCode);
	            	System.out.println("rand :"+rand);
	            	
	            	
	            	if(StringUtils.isNotBlank(verifyCode) && StringUtils.isNotBlank(rand)) {
	            		if(!verifyCode.equalsIgnoreCase(rand)) {
	            			req.setAttribute("errorMsg", "验证码不正确！");
	                		req.getRequestDispatcher("/login.jsp").forward(request, response);
	                		return false;
	            		}
	            	}else {
	            		req.setAttribute("errorMsg", "验证码不能为空！");
	            		req.getRequestDispatcher("/login.jsp").forward(request, response);
	            		return false;
	            	}
	            }
	            }
		return super.onAccessDenied(request, response);
	}
}
